# -*- coding: utf-8 -*-
import time
import logging
from datetime import datetime
from collections import defaultdict
from odoo import models, fields, api, _
from odoo.exceptions import UserError
from odoo.tools.float_utils import float_compare
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT

_logger = logging.getLogger(__name__)


class Picking(models.Model):
    _inherit = "stock.picking"

    force_date = fields.Datetime(u'强制日期', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]},copy=False)


class Quant(models.Model):
    _inherit = "stock.quant"

    @api.multi
    def _quant_update_from_move(self, move, location_dest_id, dest_package_id, lot_id=False, entire_pack=False):
        # 赋值强制日期
        move.get_self_force_date()
        res = super(Quant, self)._quant_update_from_move(move, location_dest_id, dest_package_id, lot_id=False,
                                                         entire_pack=False)
        if move.force_date:
            self.write({'in_date': move.force_date})

        return res

    @api.model
    def _quant_create_from_move(self, qty, move, lot_id=False, owner_id=False,
                                src_package_id=False, dest_package_id=False,
                                force_location_from=False, force_location_to=False):
        # 赋值强制日期
        move.get_self_force_date()

        quant = super(Quant,self)._quant_create_from_move(
            qty, move, lot_id=lot_id, owner_id=owner_id, src_package_id=src_package_id, dest_package_id=dest_package_id,
            force_location_from=force_location_from, force_location_to=force_location_to)
        if move.force_date:
            quant.in_date = move.force_date
        return quant


    # def _create_account_move_line(self, move, credit_account_id, debit_account_id, journal_id):
    #     if move.force_date:
    #         self._context['force_period_date'] = datetime.strptime(move.force_date, '%Y-%m-%d %H:%M:%S')
    #     super(Quant, self)._create_account_move_line(move, credit_account_id, debit_account_id, journal_id)

    def _create_account_move_line(self, move, credit_account_id, debit_account_id, journal_id):
        # group quants by cost
        # 赋值强制日期
        move.get_self_force_date()
        quant_cost_qty = defaultdict(lambda: 0.0)
        for quant in self:
            quant_cost_qty[quant.cost] += quant.qty
        AccountMove = self.env['account.move']
        for cost, qty in quant_cost_qty.iteritems():
            move_lines = move._prepare_account_move_line(qty, cost, credit_account_id, debit_account_id)
            if move_lines:
                if move.force_date:
                    date = datetime.strptime(move.force_date, '%Y-%m-%d %H:%M:%S')
                else:
                    date = self._context.get('force_period_date', fields.Date.context_today(self))
                new_account_move = AccountMove.create({
                    'journal_id': journal_id,
                    'line_ids': move_lines,
                    'date': date,
                    'ref': move.picking_id.name})
                new_account_move.post()



class StockMove(models.Model):
    _inherit = "stock.move"

    force_date = fields.Datetime(u'强制日期')

    @api.multi
    def get_self_force_date(self):
        for move in self:
            if move.raw_material_production_id:
                move.force_date = move.raw_material_production_id.mo_done_date
            if move.production_id:
                move.force_date = move.production_id.mo_done_date
            if move.picking_id:
                # 赋值强制日期
                if move.picking_id.force_date:
                    move.force_date = move.picking_id.force_date
            if move.inventory_id:
                if move.inventory_id.accounting_date:
                    move.force_date = move.inventory_id.accounting_date

    @api.multi
    def action_done(self):
        res = super(StockMove, self).action_done()
        pickings = self.env['stock.picking']
        self.get_self_force_date()
        f_date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
        for move in self:
            if move.force_date:
                f_date = move.force_date
        self.write({'date': f_date})
        pickings.filtered(lambda picking: picking.state == 'done').write(
            {'date_done': f_date})

        return res
